<?php

class Consignee_infoController extends CController
{
	const PAGE_SIZE=10;

	/**
	 * @var string specifies the default action to be 'list'.
	 */
	public $defaultAction='create';

	/**
	 * @var CActiveRecord the currently loaded data model instance.
	 */
	private $_model;
	
	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			array('application.filters.LoginFilter'),
			array('application.filters.AuthFilter'),
		);
	}

	/**
	 * Shows a particular model.
	 */
	public function actionShow(){	
		
		$model=$this->loadConsignee_info();
		$linkman_models=$this->loadConsignee_linkman_info();
		$this->render('show',array('model'=>$model,'linkman_models'=>$linkman_models));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'show' page.
	 */
	public function actionCreate(){
		
		$model=new Consignee_info;
		$linkman_models=array(new Consignee_linkman_info);
		if(isset($_POST['Consignee_info'])){//将所有联系人赋值 并且验证
			$model->attributes=$_POST['Consignee_info'];
			if(isset($_POST['linkman']))//判断是否存在卸货地
				$linkmans=$_POST['linkman'];
			else{
				$linkmans=array();
				$linkman_models=array();
			}
			$create=true;
			foreach($linkmans as $n=>$val){
				$linkman_model=new Consignee_linkman_info;
				$linkman_model->attributes=$val;
				$linkman_models[$n]=$linkman_model;
				$create=$linkman_model->validate()==true?$create:false;
			}
			$create=$model->validate()==true?$create:false;//验证货主信息
			if($create){//全部验证通过  添加数据库 启动事务
				$tran=$model->getDbConnection()->beginTransaction();
				try{
					$model->save(false);
					foreach($linkman_models as $val){
						$val->fk_consignee_id=$model->id;
						$val->save(false);
					}
					$tran->commit();
				}
				catch(Exception $e){
					$tran->rollBack();
					throw $e;
				}
				//$this->render('show',array('model'=>$model,'linkman_models'=>$linkman_models,'ret'=>'create','info'=>'添加成功！'));
				//return;
				$this->redirect(array('show','id'=>$model->id,'ret'=>'create','ok'=>'0'));
			}
		}
		$this->render('create',array('model'=>$model,'linkman_models'=>$linkman_models,'linkman_model_temp'=>new Consignee_linkman_info));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'show' page.
	 */
	public function actionUpdate()
	{
		$model=$this->loadConsignee_info();
		$linkman_models=$this->loadConsignee_linkman_info();
		if(isset($_POST['Consignee_info'])){//将所有联系人赋值 并且验证
			$model->attributes=$_POST['Consignee_info'];
			if(isset($_POST['linkman']))//判断是否存在货物信息
				$linkmans=$_POST['linkman'];
			else
				$linkmans=array();
			$linkmans_sum=count($linkmans);
			$linkman_models_sum=count($linkman_models);
			$update=true;
			if($linkmans_sum==$linkman_models_sum){//装货地数量没变
				foreach($linkmans as $n=>$val){
					$linkman_model=$linkman_models[$n];
					$linkman_model->attributes=$val;
					$update=$linkman_model->validate()==true?$update:false;
				}
			}
			else if($linkmans_sum>$linkman_models_sum){//装货地数量增加
				foreach($linkmans as $n=>$val){
					$linkman_model=isset($linkman_models[$n])?$linkman_models[$n]:new Consignee_linkman_info;
					$linkman_model->attributes=$val;
					$update=$linkman_model->validate()==true?$update:false;
					$linkman_models[$n]=$linkman_model;
				}
			}
			else if($linkmans_sum<$linkman_models_sum){//装货地数量减少
				foreach($linkman_models as $n=>$val){
					if(isset($linkmans[$n])){
						$val->attributes=$linkmans[$n];
						$update=$val->validate()==true?$update:false;
					}
					else
						$val->state=1;
				}
			}
			$update=$model->validate()==true?$update:false;//验证货主信息
			if($update){//全部验证通过  添加数据库
				$tran=$model->getDbConnection()->beginTransaction();
				try{
					$model->save(false);
					foreach($linkman_models as $val){
						$val->fk_consignee_id=$model->id;
						$val->save(false);
						if($val->state==1) unset($linkman_models[$n]);
					}
					$tran->commit();
				}
				catch(Exception $e){
					$tran->rollBack();
					throw $e;
				}
				//$this->render('show',array('model'=>$model,'linkman_models'=>$linkman_models,'ret'=>'admin','info'=>'更新成功！'));
				//return;
				$this->redirect(array('show','id'=>$model->id,'ret'=>'admin','ok'=>'1')+$_GET);
			}
		}
		$this->render('update',array('model'=>$model,'linkman_models'=>$linkman_models,'linkman_model_temp'=>new Consignee_linkman_info));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'list' page.
	 */
	public function actionDelete()
	{
		if(isset($_GET['id'])){
			$consignee_info=Consignee_info::model();
			$consignee_linkman_info=Consignee_linkman_info::model();
			$tran=$consignee_info->getDbConnection()->beginTransaction();
			try{
				$consignee_info->updateByPk($_GET['id'],array('state'=>1));
				$consignee_linkman_info->updateAll(array('state'=>1),array('condition'=>'fk_consignee_id='.$_GET['id']));
				$tran->commit();
			}
			catch(Exception $e){
				$tran->rollBack();
				throw $e;
			}
			unset($_GET['id']);
			$this->redirect(array('admin')+$_GET);
		}
		else
			throw new CHttpException(400,'无法获得要删除的信息ID!');
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{	
		$this->search(false);
	}
	
	public function actionSearch(){
		$this->search();
	}
	
	private function search($method=true){
		$criteria=new CDbCriteria();
		$criteria->addCondition('state=0');
		$blur=true;
		if(Yii::app()->getRequest()->isPostRequest){
			if(isset($_POST['keys'])){//页面传来的搜索关键字数组
				$_GET['keys']=$_POST['keys'];
			}
		}
		if(isset($_GET['keys'])){
			if(isset($_GET['keys']['blur'])&&$_GET['keys']['blur']=='0') $blur=false;
			foreach($_GET['keys'] as $key=>$val){
				if(trim($val)=='')
					unset($_GET['keys'][$key]);
				else if($key!='blur'){//按照模糊或精确查询
					$blur?$criteria->addSearchCondition($key,$val):$criteria->addCondition("{$key}='{$val}'");
				}
			}
		}
		$pages=new CPagination(Consignee_info::model()->count($criteria));
		$pages->pageSize=Yii::app()->params['page_size']['consignee_info'];
		$pages->applyLimit($criteria);
		
		$sort=new CSort('Consignee_info');
		$sort->applyOrder($criteria);

		$models=Consignee_info::model()->findAll($criteria);

		$this->render('admin',array(
			'models'=>$models,
			'pages'=>$pages,
			'sort'=>$sort,
			'search'=>$method,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the primary key value. Defaults to null, meaning using the 'id' GET variable
	 */
	public function loadConsignee_info($id=null)
	{
		if($this->_model===null)
		{
			if($id!==null || isset($_GET['id']))
				$this->_model=Consignee_info::model()->findbyPk($id!==null ? $id : $_GET['id']);
			if($this->_model===null)
				throw new CHttpException(404,'The requested page does not exist.');
		}
		return $this->_model;
	}
	
	public function loadConsignee_linkman_info($id=null)
	{		
		$models;
		if($id!==null || isset($_GET['id']))
			$models=Consignee_linkman_info::model()->findAllByAttributes(array('fk_consignee_id'=>($id!==null ? $id : $_GET['id']),'state'=>0));
		if($models===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $models;
	}
}
